<template>
  <a-card :bordered="false">
    <a-tabs default-active-key="1">
      <a-tab-pane key="1" tab="正在下载" >
        <div class="table-page-search-wrapper">
          <a-form layout="inline">
            <a-row :gutter="48">
              <a-col :md="5" :sm="24">
                <a-form-item label="歌名">
                  <a-input v-model="queryParam.songName" placeholder=""/>
                </a-form-item>
              </a-col>
              <a-col :md="9" :sm="24">
                <a-button type="primary" @click="$refs.table1.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="reset">重置</a-button>
<!--                <a-button style="margin-left: 8px" type="dashed" @click="tableOption">{{ optionAlertShow && '关闭' || '开启' }}提示</a-button>-->
<!--                <a-dropdown v-action:edit v-if="selectedRowKeys.length > 0 && optionAlertShow">-->
<!--                  <a-menu slot="overlay">-->
<!--                    <a-menu-item key="remove">-->
<!--                      <remove-download ref="removeDownload" :downloadIds="selectedRowKeys.join(',')" @ok="handleOk1"/>-->
<!--                    </a-menu-item>-->
<!--                  </a-menu>-->
<!--                  <a-button style="margin-left: 8px">-->
<!--                    批量操作 <a-icon type="down" />-->
<!--                  </a-button>-->
<!--                </a-dropdown>-->
              </a-col>
            </a-row>
          </a-form>
        </div>
        <s-table
          ref="table1"
          size="default"
          rowKey="key"
          :columns="columns1"
          :data="loadData1"
          :alert="options.alert"
          :rowSelection="options.rowSelection"
          showPagination="auto"
        >
          <span slot="status" slot-scope="text, record">
            <a-progress type="line" :percent="store[record.downloadId]"/>
          </span>
        </s-table>
      </a-tab-pane>
      <a-tab-pane key="2" tab="已下载" >
        <div class="table-page-search-wrapper">
          <a-form layout="inline">
            <a-row :gutter="48">
              <a-col :md="5" :sm="24">
                <a-form-item label="歌名">
                  <a-input v-model="queryParam.songName" placeholder=""/>
                </a-form-item>
              </a-col>
              <a-col :md="9" :sm="24">
                <a-button type="primary" @click="$refs.table2.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="reset">重置</a-button>
                <a-button style="margin-left: 8px" type="dashed" @click="tableOption">{{ optionAlertShow && '关闭' || '开启' }}提示</a-button>
                <a-dropdown v-action:edit v-if="selectedRowKeys.length > 0 && optionAlertShow">
                  <a-menu slot="overlay">
                    <a-menu-item key="remove">
                      <remove-download ref="removeDownload" :downloadIds="selectedRowKeys.join(',')" @ok="handleOk2"/>
                    </a-menu-item>
                  </a-menu>
                  <a-button style="margin-left: 8px">
                    批量操作 <a-icon type="down" />
                  </a-button>
                </a-dropdown>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <s-table
          ref="table2"
          size="default"
          rowKey="key"
          :columns="columns2"
          :data="loadData2"
          :alert="options.alert"
          :rowSelection="options.rowSelection"
          showPagination="auto"
        >
          <span slot="action" slot-scope="text, record">
            <template>
              <remove-download ref="removeDownload" :downloadIds="String(record.downloadId)" @ok="handleOk2"/>
            </template>
          </span>
        </s-table>
      </a-tab-pane>
      <a-tab-pane key="3" tab="下载失败" >
        <div class="table-page-search-wrapper">
          <a-form layout="inline">
            <a-row :gutter="48">
              <a-col :md="5" :sm="24">
                <a-form-item label="歌名">
                  <a-input v-model="queryParam.songName" placeholder=""/>
                </a-form-item>
              </a-col>
              <a-col :md="9" :sm="24">
                <a-button type="primary" @click="$refs.table3.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="reset">重置</a-button>
                <a-button style="margin-left: 8px" type="dashed" @click="tableOption">{{ optionAlertShow && '关闭' || '开启' }}提示</a-button>
                <a-dropdown v-action:edit v-if="selectedRowKeys.length > 0 && optionAlertShow">
                  <a-menu slot="overlay">
                    <a-menu-item key="remove">
                      <remove-download ref="removeDownload" :downloadIds="selectedRowKeys.join(',')" @ok="handleOk3"/>
                    </a-menu-item>
                  </a-menu>
                  <a-button style="margin-left: 8px">
                    批量操作 <a-icon type="down" />
                  </a-button>
                </a-dropdown>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <s-table
          ref="table3"
          size="default"
          rowKey="key"
          :columns="columns2"
          :data="loadData3"
          :alert="options.alert"
          :rowSelection="options.rowSelection"
          showPagination="auto"
        >
          <span slot="action" slot-scope="text, record">
            <template>
              <remove-download ref="removeDownload" :downloadIds="String(record.downloadId)" @ok="handleOk3"/>
            </template>
          </span>
        </s-table>
      </a-tab-pane>
    </a-tabs>
  </a-card>
</template>

<script>
  // import moment from 'moment'
  import { STable } from '@/components'
  import { query, update, judgeFailed } from '@/api/music/download'
  import RemoveDownload from './modules/download/RemoveDownload'

  export default {
    name: 'CollectionPlaylistDetail',
    components: {
      STable,
      RemoveDownload
    },
    data () {
      return {
        // 高级搜索 展开/关闭
        advanced: false,
        // 查询参数
        queryParam: {},
        store: {},
        oldStore: {},
        albums: [],
        index: -1,
        intervalId: -1,
        // 表头
        columns1: [
          {
            title: '歌名',
            dataIndex: 'songName',
            align: 'center',
            sorter: true
          },
          {
            title: '歌手',
            dataIndex: 'singerName',
            align: 'center'
          },
          {
            title: '专辑',
            dataIndex: 'albumName',
            align: 'center',
            sorter: true
          },
          {
            title: '下载进度',
            dataIndex: 'downloadStatus',
            scopedSlots: { customRender: 'status' },
            align: 'center'
          }
        ],
        columns2: [
          {
            title: '歌名',
            dataIndex: 'songName',
            align: 'center',
            sorter: true
          },
          {
            title: '歌手',
            dataIndex: 'singerName',
            align: 'center'
          },
          {
            title: '专辑',
            dataIndex: 'albumName',
            align: 'center',
            sorter: true
          },
          {
            title: '下载时间',
            dataIndex: 'gmtCreate',
            align: 'center'
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: 'center',
            scopedSlots: { customRender: 'action' }
          }
        ],
        // 加载数据方法 必须为 Promise 对象
        loadData1: parameter => {
          // 统一处理查询参数，便于后端表格DTO用固定参数接收
          this.queryParam.downloadStatus = 3
          const queryJson = { 'queryParam': JSON.stringify(this.queryParam) }
          return query(Object.assign(parameter, queryJson))
            .then(res => {
              return res.data.result
            })
        },
        loadData2: parameter => {
          // 统一处理查询参数，便于后端表格DTO用固定参数接收
          this.queryParam.downloadStatus = 1
          const queryJson = { 'queryParam': JSON.stringify(this.queryParam) }
          return query(Object.assign(parameter, queryJson))
            .then(res => {
              return res.data.result
            })
        },
        loadData3: parameter => {
          // 统一处理查询参数，便于后端表格DTO用固定参数接收
          this.queryParam.downloadStatus = 4
          const queryJson = { 'queryParam': JSON.stringify(this.queryParam) }
          return query(Object.assign(parameter, queryJson))
            .then(res => {
              return res.data.result
            })
        },
        selectedRowKeys: [],
        selectedRows: [],

        // custom table alert & rowSelection
        options: {
          alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
          rowSelection: {
            selectedRowKeys: this.selectedRowKeys,
            onChange: this.onSelectChange
          }
        },
        optionAlertShow: true,
        playlist: {}
      }
    },
    created () {
      this.tableOption()
      window.addEventListener('setItem', this.listener)
      this.judgeFailed()
      this.intervalId = setInterval(() => {
        this.judgeFailed()
        this.$refs.table1.refresh(true)
      }, 60000)
    },
    beforeDestroy () {
      window.removeEventListener('setItem', this.listener)
      clearInterval(this.intervalId)
    },
    methods: {
      tableOption () {
        if (!this.optionAlertShow) {
          this.options = {
            alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
            rowSelection: {
              selectedRowKeys: this.selectedRowKeys,
              onChange: this.onSelectChange
            }
          }
          this.optionAlertShow = true
        } else {
          this.options = {
            alert: false,
            rowSelection: null
          }
          this.optionAlertShow = false
        }
      },
      judgeFailed () {
        judgeFailed()
          .then(res => {
            if (res.data.message === 'error') {
              this.$message.error('更新下载失败')
            }
          })
      },
      listener () {
        this.store = JSON.parse(sessionStorage.getItem(String(this.$store.getters.userInfo.id)))
        for (const key in this.store) {
          if (this.oldStore[key] !== 100 && this.store[key] === 100) {
            update({ 'status': 1, 'downloadId': parseInt(key) })
              .then(res => {
                if (res.data.message !== 'error') {
                  this.$refs.table1.refresh(true)
                } else {
                  this.$message.error('下载失败！')
                }
              })
          }
        }
        this.oldStore = this.store
      },
      handleOk1 () {
        this.$refs.table1.clearSelected()
        this.$refs.table1.refresh(false)
        this.$message.success('操作成功！')
      },
      handleOk2 () {
        this.$refs.table2.clearSelected()
        this.$refs.table2.refresh(false)
        this.$message.success('操作成功！')
      },
      handleOk3 () {
        this.$refs.table3.clearSelected()
        this.$refs.table3.refresh(false)
        this.$message.success('操作成功！')
      },
      onSelectChange (selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectedRows = selectedRows
      },
      reset () {
        this.queryParam = {}
      }
    },
    filters: {
      statusFilter (status) {
        if (status === 1) {
          return '已下载'
        } else if (status === 3) {
          return '正在下载'
        } else if (status === 4) {
          return '下载失败'
        }
      }
    }
  }
</script>
